/*Spring Boot 控制器（Controller），负责处理与“标准工作监察问题审查”相关的HTTP请求，
调用服务层（Service）完成业务逻辑，并返回统一格式的响应。*/



/*包声明与导入*/
/*声明控制器类位于 com.example.controller 包*/
package com.example.controller;


/*
导入必要的依赖：
Result：统一响应封装类（通常包含状态码、消息、数据等字段）。
standardWorkSupervisePojo：数据模型类，用于接收请求体或返回数据。
standardWorkSuperviseService：服务层接口，用于处理业务逻辑。
Spring注解：@Autowired（依赖注入）、@PostMapping（定义POST请求路由）、@RequestBody（解析请求体为对象）。
*/
import com.example.pojo.*;
import com.example.service.auditProblemListService;
import com.example.service.basicAuditInstructionService;
import com.example.service.standardWorkSuperviseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;


/*标记该类为Spring MVC控制器，所有方法默认返回JSON/XML响应（无需额外加@ResponseBody）*/
@RestController

public class toExamineProblemController {
    /*自动注入 standardWorkSuperviseService 的实现类（由Spring容器管理），用于调用业务逻辑。*/
    @Autowired
    private standardWorkSuperviseService standardWorkSuperviseService;
    @Autowired
    private basicAuditInstructionService basicAuditInstructionService;
    @Autowired
    private auditProblemListService auditProblemListService;
    @Value("${file.upload-dir}")
    private String saveDir;

    //插入一行监察标准要求
    /*路由：POST /insertOneStandardWorkSuperviseToExamineProblem
    @RequestBody：将请求体中的JSON自动解析为 standardWorkSupervisePojo 对象。
    逻辑：
    *返回统一成功的响应（Result.success）。
    */
    @PostMapping("/insertOneStandardWorkSuperviseToExamineProblem")
    public Result insertOneStandardWorkSuperviseToExamineProblem(@RequestBody standardWorkSupervisePojo pojo){
        standardWorkSuperviseService.insertOne(pojo);// 调用服务层插入数据
        return Result.success("插入成功/ok");// 返回成功响应
    }
    //修改一行信息
    @PostMapping("/editOneByIdStandardWorkSuperviseToExamineProblem")
    public Result editOneByIdStandardWorkSuperviseToExamineProblem(@RequestBody standardWorkSupervisePojo pojo) {
        standardWorkSuperviseService.editOneById(pojo);// 调用服务层插入数据
        return Result.success("修改成功");// 返回成功响应
    }
    //查询所有的监察记录
    @PostMapping("/inquiryAllStandardWorkSuperviseToExamineProblem")
    public Result inquiryAllStandardWorkSuperviseToExamineProblem(){
        List<standardWorkSupervisePojo> pojoList=standardWorkSuperviseService.inquiryAll();
        return Result.success(pojoList);
    }

    //——————————————————————————————————————————————审核块—————————————————————————————————————————————
    //插入一行审核块
    @PostMapping("/insertOneStandardModuleToExamineProblem")
    public Result insertOneStandardModuleToExamineProblem(@RequestBody basicAuditInstructionPojo pojo){
        basicAuditInstructionService.insertOne(pojo);
        return Result.success("插入成功");
    }
    //修改一行审核块
    @PostMapping("/editStandardModuleToExamineProblem")
    public Result editStandardModuleToExamineProblem(@RequestBody basicAuditInstructionPojo pojo) {
        basicAuditInstructionService.editOneById(pojo);
        return Result.success("修改成功");
    }

    //根据分页查询审核块
    @PostMapping("/queryStandardModulePaginationToExamineProblem")
    public Result queryStandardModulePaginationToExamineProblem(@RequestBody Map<String,Object> map){
        List<basicAuditInstructionPojo> basicAuditInstructionPojos=basicAuditInstructionService.queryByPage(map);
        return Result.success(basicAuditInstructionPojos);
    }

    //查询所有审核块条数
    @PostMapping("/queryStandardModuleQuantityToExamineProblem")
    public Result queryStandardModuleQuantityToExamineProblem(){
        Integer quantity= basicAuditInstructionService.queryQuantity();
        return Result.success(quantity);
    }

    //根据一个字段修改一个字段
    @PostMapping("/editByOneFieldToExamineProblem")
    public Result editByOneFieldToExamineProblem(@RequestBody Map<String,Object> map){
        String id = (String) map.get("id");
        String fieldName = (String) map.get("fieldName");
        String fieldValue = (String) map.get("fieldValue");
        basicAuditInstructionService.editOneField(id,fieldName,fieldValue);
        return Result.success("修改成功");
    }

    //上传审核块作业指导书的附件（图片、视频）
    @PostMapping("/editInstructionFileToExamineProblem")
    public Result editInstructionFileToExamineProblem(
            @RequestParam("file") MultipartFile file,
            @RequestParam String id,
            @RequestParam String fileName,
            @RequestParam String fieldName,
            @RequestParam String fieldValue){
        try {
            if (!file.isEmpty()) {
                String filePath = saveDir + fileName;
                File dest = new File(filePath);
                // 将文件保存到服务器上的指定位置
                file.transferTo(dest);
                System.out.println("保存成功");
                basicAuditInstructionService.editOneField(id, fieldName, fieldValue);
            }
            return Result.success("保存成功");
        }
        catch (IOException e) {
            // 捕获异常并返回错误消息
            throw new RuntimeException("文件保存失败：" + e.getMessage());
        }
    }

    //删除审核块作业指导书的附件（图片、视频）
    @PostMapping ("/deleteInstructionFileToExamineProblem")
    public Result deleteInstructionFileToExamineProblem(@RequestBody Map<String,Object> map){
        // 先删除旧文件
        String id = (String) map.get("id");
        String fieldName = (String) map.get("fieldName");
        String fieldValue = (String) map.get("fieldValue");
        String fileName = (String) map.get("fileName");
        //删除文件
        String filePath =saveDir + fileName;
        System.out.println(filePath);
        // 使用 Paths 类的静态方法 get 来根据给定的文件路径字符串 filePath 创建一个 Path 对象
        Path path = Paths.get(filePath);
        try {
            Files.delete(path);
            //删除文件后，修改数据表中存储文件路径的字段
            basicAuditInstructionService.editOneField(id,fieldName,fieldValue);
            System.out.println(map);
            return Result.success("删除成功");
        }
        catch (IOException e) {
            System.err.println("删除文件时出错: " + e.getMessage());
            //调用service层修改数据库信息
            //删除文件后，修改数据表中存储文件路径的字段
            basicAuditInstructionService.editOneField(id,fieldName,fieldValue);
            return Result.success("删除文件时出错");
        }
    }

    //下载审核块作业指导书的附件（图片、视频）
    @GetMapping("/downloadInstructionFileToExamineProblem")
    public Result downloadInstructionFileToExamineProblem(@RequestParam("fileName") String fileName){
        byte[] file= basicAuditInstructionService.readFile(fileName);
        return Result.success(file);
    }

    //——————————————————————————————————————————————审核问题—————————————————————————————————————————————
    //插入一行审核问题
    @PostMapping("/insertOneAuditProblemToExamineProblem")
    public Result insertOneAuditProblemToExamineProblem(@RequestBody auditProblemListPojo pojo){
        auditProblemListService.insertOne(pojo);
        return Result.success("插入成功");
    }
    //修改一行审核问题
    @PostMapping("/editAuditProblemToExamineProblem")
    public Result editAuditProblemToExamineProblem(@RequestBody auditProblemListPojo pojo) {
        auditProblemListService.editOneById(pojo);
        return Result.success("修改成功");
    }

    //根据分页查询审核问题
    @PostMapping("/queryAuditProblemPaginationToExamineProblem")
    public Result queryAuditProblemPaginationToExamineProblem(@RequestBody Map<String,Object> map){
        List<auditProblemListPojo> auditProblemListPojos=auditProblemListService.queryByPage(map);
        return Result.success(auditProblemListPojos);
    }

    //查询所有审核问题条数
    @PostMapping("/queryAuditProblemQuantityToExamineProblem")
    public Result queryAuditProblemQuantityToExamineProblem(){
        Integer quantity= auditProblemListService.queryQuantity();
        return Result.success(quantity);
    }

    //上传审核问题文件
    @PostMapping("/addAuditProblemFileToExamineProblem")
    public Result addAuditProblemFileToExamineProblem(
            @RequestParam("file") MultipartFile file,
            @RequestParam String id,
            @RequestParam String problem_photo,
            @RequestParam String fileName){
        try {
            if (!file.isEmpty()) {
                String filePath = saveDir + fileName;
                File dest = new File(filePath);
                // 将文件保存到服务器上的指定位置
                file.transferTo(dest);
                System.out.println("保存成功");
                String fieldName="problem_photo";
                String fieldValue=problem_photo;
                auditProblemListService.editOneField(id, fieldName, fieldValue);
            }
            return Result.success("保存成功");
        }
        catch (IOException e) {
            // 捕获异常并返回错误消息
            throw new RuntimeException("文件保存失败：" + e.getMessage());
        }
    }

    //删除审核问题中上传的某个附件
    @PostMapping ("/deleteFileNameToExamineProblem")
    public Result deleteFileNameToExamineProblem(@RequestBody Map<String,Object> map){
        // 先删除旧文件
        String id = (String) map.get("id");
        String fieldName = (String) map.get("fieldName");
        String fieldValue = (String) map.get("fieldValue");
        String fileName = (String) map.get("fileName");
        //删除文件
        String filePath =saveDir + fileName;
        System.out.println(filePath);
        // 使用 Paths 类的静态方法 get 来根据给定的文件路径字符串 filePath 创建一个 Path 对象
        Path path = Paths.get(filePath);
        try {
            Files.delete(path);
            //删除文件后，修改数据表中存储文件路径的字段
            auditProblemListService.editOneField(id,fieldName,fieldValue);
            System.out.println(map);
            return Result.success("删除成功");
        }
        catch (IOException e) {
            System.err.println("删除文件时出错: " + e.getMessage());
            //调用service层修改数据库信息
            //删除文件后，修改数据表中存储文件路径的字段
            auditProblemListService.editOneField(id,fieldName,fieldValue);
            return Result.success("删除文件时出错");
        }
    }

    @PostMapping("/addDocxDocumentToExamineProblem")
    public Result addDocxDocumentToExamineProblem(
            @RequestParam("file") MultipartFile file,
            @RequestParam String fileName){
        System.out.println(file);
        System.out.println(fileName);
        return Result.success ("接收成功");
    }
}
